package com.fang.security.core.social.qq.api;

import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * accessToken，获取令牌
 * restTemplate，发送http请求
 * 参考QQ互联
 * 6.最后一步
 */
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ{

	private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";
	
	private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";
	
	private String appId;
	
	private String openId;
	
	//
	private ObjectMapper objectMapper = new ObjectMapper();
	
	public QQImpl(String accessToken,String appId){
		super(accessToken,TokenStrategy.ACCESS_TOKEN_PARAMETER);
		this.appId = appId;
		String url = String.format(URL_GET_OPENID,accessToken);
		String result = getRestTemplate().getForObject(url, String.class);
		//callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} )
		System.out.println(result);
		this.openId = StringUtils.substringBetween(result, "\"openid\":","}");
	}
	
	@Override
	public QQUserInfo getQQUserInfo(){
		String url = String.format(URL_GET_USERINFO, openId,appId);
		String result = getRestTemplate().getForObject(url, String.class);
		System.out.println(result);
		QQUserInfo obj = null;
		try {
			 obj= objectMapper.readValue(result, QQUserInfo.class);
			 obj.setOpenId(openId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}

}
